#include "mat_char_animation.h"
#include "mat_sfx_manager.h"
#include "mat_define.h"

#include "ui/ui_manager.h"
#include "ui/ui_flexeffect.h"


MATCharAnimation::MATCharAnimation() : m_LoopCount(0)
{
	ui::UIWidget* pChar = ui::UIManager::Instance().GetWidget("dwarf");

	SetAnimation(ANIMATION_IDLE);
	//m_BipedChar.SetFlipped(true);
	m_BipedChar.SetPos(pChar->GetPosition());
	const float Scale = (float)GraphicsUtil::WIDTH / (float)TEXTURE_WIDTH;
	m_BipedChar.OBJECT_SCALE = Scale;
	//m_BipedChar.SetPos(math::Vec2(0.5f,0.5f));   //(pChar->GetPosition());	
	
}

MATCharAnimation&	MATCharAnimation::Instance()
{
	static MATCharAnimation inst;
	return inst;
}


void	MATCharAnimation::SetAnimation(ANIMATION_TYPE Type)
{
	switch(Type)
	{
	case ANIMATION_IDLE:
		m_LoopCount = 1;
		m_BipedChar.SetAnimation("idle",true);	
		break;

	case ANIMATION_LAUGH:
		if(m_CurrentAnimation == ANIMATION_IDLE)
		{
			m_LoopCount = 2;
			m_BipedChar.SetAnimation("laugh",true);
			
		}
		break;

	case ANIMATION_SURPRISE:
			m_LoopCount = 1;
			m_BipedChar.SetAnimation("surprised",true);
		
		break;

	}
	m_CurrentAnimation = Type;
	m_BipedChar.LoadDefaults();
}

void	MATCharAnimation::Tick(float dt)
{
	bool IsFinish = m_BipedChar.Tick(dt);
	
	if( !IsFinish && m_CurrentAnimation != ANIMATION_IDLE)
	{

		m_LoopCount--;
		if(m_LoopCount <= 0)
		{
			if(m_CurrentAnimation == ANIMATION_SURPRISE)
			{
				m_LoopCount = 1;
				m_BipedChar.SetAnimation("laugh",true);
				m_CurrentAnimation = ANIMATION_LAUGH;
			}
			else
			{
				SetAnimation(MATCharAnimation::ANIMATION_IDLE);
				
			}
		}
		//else
		//	m_BipedChar.SetAnimation(m_BipedChar.GetAnimation(),true);
	}

}

void	MATCharAnimation::Render()
{
	
	m_BipedChar.Render(math::Vec2(0,0));
	
}

void	MATCharAnimation::KeyPressed(input::Keyboard::KEY* pKey)
{
	switch(pKey->KeyID)
	{
	case KEY_F5:
			//m_BipedChar.Clear();
			bones::BipedAnimationSet::Instance().RefreshAll();
			bones::BipedAnimationSet::Instance();
			
			bones::BipedAnimationSet::Instance().AddAnimationLua("anim/idle.sbp");
			bones::BipedAnimationSet::Instance().AddAnimationLua("anim/laugh.sbp");
			bones::BipedAnimationSet::Instance().AddAnimationLua("anim/surprised.sbp");

			m_BipedChar.SetAnimation( m_BipedChar.GetAnimation() ,true);
		break;
	}
}
